package com.v.im.imservice.netty.handle;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.v.im.commonmodule.utils.chat.ChatUtils;
import com.v.im.commonmodule.utils.chat.Message;
import com.v.im.commonmodule.utils.chat.SendInfo;
import com.v.im.commonmodule.utils.response.ImResponse;
import com.v.im.imservice.kafka.producer.ImKafkaProducer;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.IOException;
import java.net.InetSocketAddress;

@Component
@Scope("prototype")
@ChannelHandler.Sharable
public class NettyServerHandler  extends SimpleChannelInboundHandler<String> {

    /**
     * 日志
     */
    private Logger log = LoggerFactory.getLogger(getClass());

    @Resource
    private ImKafkaProducer imKafkaProducer;

    private NettyServerHandler nettyServerHandler;

    @PostConstruct
    public void init() {
        nettyServerHandler = this;
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws JsonProcessingException {
        ImResponse imResponse =ImResponse.SUCCESS;
        log.info(msg);
        ObjectMapper objectMapper = new ObjectMapper();
        SendInfo sendInfo = null;
        try {
            sendInfo = objectMapper.readValue(msg, SendInfo.class);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //心跳检测包
        if (ChatUtils.MSG_PING.equals(sendInfo.getCode())) {
            imResponse.setData(msg);
        }
        //真正的消息
        if (ChatUtils.MSG_MESSAGE.equals(sendInfo.getCode())) {
            Message message = sendInfo.getMessage();
            message.setMine(false);
            imResponse.setData((objectMapper.writeValueAsString(sendInfo)));
            //单聊
            if (ChatUtils.FRIEND.equals(message.getType())) {
                nettyServerHandler.imKafkaProducer.sendFriendMessage(message);
            }
            //群聊
            if (ChatUtils.CROWD.equals(message.getType())) {
                nettyServerHandler.imKafkaProducer.sendCrowdMessage(message);
            }
        }
        //准备就绪，需要发送离线消息
        if (ChatUtils.MSG_READY.equals(sendInfo.getCode())) {

        }

        /*ctx.writeAndFlush(msg);*/
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        InetSocketAddress insocket = (InetSocketAddress) ctx.channel().remoteAddress();
        String clientIp = insocket.getAddress().getHostAddress();
        log.info("收到客户端[ip:" + clientIp + "]连接");
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 当出现异常就关闭连接
        ctx.close();
    }
}
